package com.example.bbs.controller.config;

import com.example.bbs.entity.User;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author jiajiazi
 * @version 1.0
 * @date 2021/5/1 0:29
 */

public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        try {
            System.out.println("user登录拦截");
            //统一拦截（查询当前session是否存在user）(这里user会在每次登陆成功后，写入session)
            String requestURL = String.valueOf(request.getRequestURL());

            System.out.println(requestURL);
            User user = (User) request.getSession().getAttribute("user");
            if (user != null) {
                System.out.println("session user true");
                return true;
            }
            System.out.println("session user false");
            response.sendRedirect(request.getContextPath() + "/");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;


        //System.out.println("进入拦截器");
        //String requestURL = String.valueOf(request.getRequestURL());
        //System.out.println(requestURL);
        //boolean loginrequest = false;
        //if (requestURL.endsWith("/loginpage")) {
        //    loginrequest = true;
        //}
        //User user=(User)request.getSession().getAttribute("user");
        //if (user==null) {
        //    if (loginrequest) {
        //        System.out.println("登录请求，用户信息session不存在，继续响应进入登录页");
        //        return true;
        //    } else {
        //        System.out.println("用户非登录请求，用户信息session不存在，拦截，跳转登录");
        //        response.sendRedirect("/indexs/loginpage");
        //        return false;
        //    }
        //}else{
        //    if (loginrequest) {
        //        System.out.println("登录请求，用户信息session存在，直接进入用户页（免登陆）");
        //        response.sendRedirect("/indexs/readmessage");
        //        return false;
        //    } else {
        //        System.out.println("用户非登录请求，用户信息session存在，继续业务");
        //        return true;
        //    }
        //}
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    }

}
